package com.sensetime.encodevideo;

import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.projection.MediaProjection;
import android.view.Display;
import android.view.Surface;

import java.io.IOException;
import java.nio.ByteBuffer;

public class H264Encoder extends Thread{
    private MediaProjection mediaProjection;
    private MediaCodec mediaCodec;
    private boolean isRunning = true;
    VirtualDisplay virtualDisplay ;
    public H264Encoder(MediaProjection mediaProjection){
        this.mediaProjection = mediaProjection;
        try {
            int width = 1080;
            int height = 720;
            MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height);
            mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 30);//i帧的间隔
            format.setInteger(MediaFormat.KEY_BIT_RATE, width*height);

            //录屏的数据先存放到mediaCodec提供的surface缓存

            //说明来自surface的数据
            format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);

            //最后一个参数表明mediaCodec这是编码操作
            mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

            Surface surface = mediaCodec.createInputSurface();//这个就是准备的缓存数据的surface

            virtualDisplay = mediaProjection.createVirtualDisplay("only one",
                    width, height, 3, DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
                    surface, null,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run(){
        mediaCodec.start();
        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
        while(isRunning){
            //这个就是系统编码返回的接客人走的小姐姐的编号，通过下标可以得到数据ByteBuffer
            int outIndex = mediaCodec.dequeueOutputBuffer(info, 10000);
            if(outIndex>=0){
                ByteBuffer buffer = mediaCodec.getOutputBuffer(outIndex);
                byte[]data = new byte[info.size];
                buffer.get(data);//将数据转移到了byte[]中
                FileUtils.write(data);
                FileUtils.writeContent(data);
                mediaCodec.releaseOutputBuffer(outIndex, false);
            }

        }
    }
    public void stopRecord(){
        isRunning = false;
        mediaProjection.stop();
        virtualDisplay.release();
    }
}
